/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('page_chapter')].slice(-1)
  let url = lastNrPage.querySelector('ul li:nth-child(3) a')

  const response = await fetch(url)
  const decoder = new TextDecoder('utf8')
  const html = decoder.decode(await response.arrayBuffer())

  let div = document.createElement('div')
  div.innerHTML = html
  
  div.querySelector('.novelcontent').style.marginTop = '50px'
  div.querySelector('.novelcontent').style.marginBottom = '50px'
  
  let alink = document.createElement('a')
  alink.href = url
  alink.className = 'p2'
  alink.innerText = '本页'
  let liDome = document.createElement('li')
  liDome.append(alink)
  div.querySelectorAll('.page_chapter ul').forEach(pageDom => {
    pageDom.insertBefore(liDome.cloneNode(true), pageDom.children[3])
    pageDom.removeChild(pageDom.children[4])
  })
  
  cleanPage(div)
  
  fixPc(div)
  
  div.querySelector('.page_chapter').style.marginBottom = '0'

  let [lastContent] = [...document.getElementsByClassName('nr_layout')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return {div, url}
}

/**从页面获取书名 */
function getBookName() {
  let bookName = ''
  let homePageTilteDom = document.querySelector('.tab .p1')
  if ( homePageTilteDom ) {
    return homePageTilteDom.innerText
  }
  let matchResult = document.title.match(/(.*)_(.*)-/)
  if ( matchResult ) {
    bookName = matchResult[2]
  }
  return bookName
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.nr_layout', '.head .nav_name h1', dom, url)
}


/**包装cleanPage方法 */
function cleanPage(context = document) {
  $chromePlugin.cleanPage(context, ['.nr_function1 + .page_chapter', '.nr_function1', '.footer', '#neirong_1', '#neirong_2', '#neirong_3', '#neirong_1_html', '#neirong_2_html', '#neirong_3_html'])
}

/** 修改页面样式，优化pc端的阅读体验 */
function fixPc (dom = document) {
  if (window.innerWidth < 900)  {
    return
  }
  if (dom.querySelector('body') != null){
    dom.querySelector('body').style.backgroundColor='rgba(0,100,150,.2)'
  }
  let novelbody = dom.querySelector('#novelbody')
  novelbody.style.maxWidth = '1000px'
  novelbody.style.width = '90%'
  novelbody.style.margin = '0 auto'
  novelbody.style.backgroundColor = 'rgba(255,255,255,.3)'
}

$chromePlugin.loadQueueFn.push(cleanPage, fixPc)

$chromePlugin.loadQueueFn.push(cleanPage)